package com.cvpoc.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.cvpoc.exception.BusinessException;
import com.cvpoc.service.FileService;

public class FileServiceImlp implements FileService {

	@Override
	public void download( HttpServletResponse pResponse,String pFilePath) throws BusinessException {
		// return an application file instead of html page
		pResponse.setContentType("application/octet-stream");
		pResponse.setHeader("Content-Disposition",
				"attachment;filename=formationInitiale.pdf");
		try{
			if (StringUtils.isNotBlank(pFilePath)) {
				// Get it from file system
				FileInputStream in = new FileInputStream(new File(
						pFilePath));
				// Get it from web path
				// jndi:/localhost/StrutsExample/upload/superfish.zip
				// URL url = getServlet().getServletContext()
				// .getResource("upload/superfish.zip");
				// InputStream in = url.openStream();

				// Get it from bytes array
				// byte[] bytes = new byte[4096];
				// InputStream in = new ByteArrayInputStream(bytes);
				ServletOutputStream out = pResponse.getOutputStream();

				byte[] outputByte = new byte[4096];
				// copy binary content to output stream
				while (in.read(outputByte, 0, 4096) != -1) {
					out.write(outputByte, 0, 4096);
				}
				in.close();
				out.flush();
				out.close();
			}
		}catch (IOException ex){
			throw new BusinessException("download.erreur");
		}
	}

}
